﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;

namespace QuanLyNhaSach.MainMenu
{
    public partial class FrmReceivingBook : DevComponents.DotNetBar.Office2007Form
    {
        int _MinQuantity;
        float _oldPrice;
        public ActionName Action { get; set; }
        ReceivingBUS receiBUS;

        public FrmReceivingBook()
        {
            InitializeComponent();
            cmbBook.DisplayMember = BookColumn.BookName.ToString();
            receiBUS = new ReceivingBUS();
            cmbBook.ValueMember = BookColumn.BookID.ToString();
            colReceivePrice.DefaultCellStyle.Format = Global.CurrencyFormat;
            dtgReceiving.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dtgReceiving_EditingControlShowing);
        }

        void dtgReceiving_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            ComboBox cmbBox;
            if (dtgReceiving.CurrentCell.ColumnIndex == cmbBook.Index)
            {
                cmbBox = e.Control as ComboBox;
                if (cmbBox != null)
                {
                    //cmbBox.SelectedValueChanged += new EventHandler(cmbBox_SelectedValueChanged);
                    cmbBox.SelectedIndexChanged += cmbBox_SelectedValueChanged;
                    cmbBox.DropDownStyle = ComboBoxStyle.DropDown;
                    cmbBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    cmbBox.AutoCompleteSource = AutoCompleteSource.ListItems;
                }
            }
        }

        void cmbBox_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                
                SetMessage(string.Empty, true);
                ComboBox cmbBox = (ComboBox)sender;
                cmbBox.SelectedIndexChanged -= cmbBox_SelectedValueChanged;
                if (Global.intParse(cmbBox.SelectedValue) > 0)
                {
                    int bookID = int.Parse(cmbBox.SelectedValue.ToString());

                    BookBUS bookBUS = new BookBUS();
                    BookDTO bookDto = bookBUS.GetBookByID(bookID);
                    ParameterBUS parameterBUS = new ParameterBUS();
                    if (bookDto != null)
                    {
                        _MinQuantity = parameterBUS.GetParameterValueByCode(ParameterCode.MinReceiving.ToString());
                        dtgReceiving.CurrentRow.Cells[colBookID.Index].Value = bookDto.BookID;
                        dtgReceiving.CurrentRow.Cells[colReceivePrice.Index].Value = bookDto.ReceivePrice;
                        dtgReceiving.CurrentRow.Cells[colAuthor.Index].Value = bookDto.AuthorName;
                        dtgReceiving.CurrentRow.Cells[colCategory.Index].Value = bookDto.CategoryName;
                        dtgReceiving.CurrentRow.Cells[colStockQuantity.Index].Value = bookDto.StockQuantity;
                        dtgReceiving.CurrentRow.Cells[colQuantity.Index].Value = _MinQuantity;
                        ComputeGrandTotal();
                    }

                    int lastRow = dtgReceiving.Rows.GetLastRow(DataGridViewElementStates.None);
                    if (lastRow > dtgReceiving.CurrentRow.Index &&
                        dtgReceiving[colBookID.Index, lastRow].Value != null)
                    {
                        dtgReceiving.Rows.Add(1);
                    }
                    else if (lastRow == dtgReceiving.CurrentRow.Index)
                    {
                        dtgReceiving.Rows.Add(1);
                    }
                }
                else
                {
                    ClearValueGrid(dtgReceiving.CurrentRow.Index);
                }
                cmbBox.SelectedIndexChanged += cmbBox_SelectedValueChanged;
            }
            catch(FormatException ex)
            {
                Global.SetMessage(lblMessage, ex.Message, false);
            }
        }

        private void ClearValueGrid(int index)
        {
            SetMessage(string.Empty, true);
            dtgReceiving[colBookID.Index, index].Value = null;
            dtgReceiving[colReceivePrice.Index, index].Value = null;
            dtgReceiving[colAuthor.Index, index].Value = null;
            dtgReceiving[colCategory.Index, index].Value = null;
            dtgReceiving[colStockQuantity.Index, index].Value = null;
            dtgReceiving[colQuantity.Index, index].Value = null;
        }

        private void FrmReceivingBook_Load(object sender, EventArgs e)
        {
            LoadDocSequenceAndCombobox();
        }

        private void LoadDocSequenceAndCombobox()
        {
            SetMessage(string.Empty, true);
            DocSequenceBUS docSeqBUS = new DocSequenceBUS();
            txtReceivingCode.Text = docSeqBUS.GetNextDocSequenceNumber(DocSequence.Receiving.ToString());
            dtpCreateDate.Value = DateTime.Now;
            txtDescription.Clear();

            BookBUS bookBUS = new BookBUS();
            cmbBook.DataSource = bookBUS.GetNewBindingList();

            dtgReceiving.Rows.Clear();
            txtGrandTotal.Clear();
            dtgReceiving.Rows.Add(1);
            ProcessButton();
        }

        private void dtgReceiving_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            dtgReceiving[colDel.Index, e.RowIndex].Value = Properties.Resources.deletered;
            Global.GenerateNumber(dtgReceiving, colNumber.Index);
        }

        private void dtgReceiving_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                SetMessage(string.Empty, true);
                if (e.ColumnIndex == colQuantity.Index)
                {
                    if (dtgReceiving[colBookID.Index, e.RowIndex].Value != null && dtgReceiving[e.ColumnIndex, e.RowIndex].Value != null)
                    {
                         int newValue = 0;
                        if(int.TryParse(dtgReceiving[e.ColumnIndex, e.RowIndex].Value.ToString(),out newValue))
                        {
                            if (newValue < _MinQuantity)
                            {
                                Global.SetMessage(lblMessage, "Số lượng nhập phải lớn hơn số lượng nhập tối thiểu theo quy định", false);
                                dtgReceiving[e.ColumnIndex, e.RowIndex].Value = _MinQuantity;
                            }

                            ComputeGrandTotal();
                        }
                    }
                }
                if (e.ColumnIndex == colReceivePrice.Index)
                {
                    
                    if (dtgReceiving[e.ColumnIndex, e.RowIndex].Value != null)
                    {
                        float price = 0;
                        if(float.TryParse(dtgReceiving[e.ColumnIndex, e.RowIndex].Value.ToString(),out price))
                        {
                            if (price <= 0)
                            {
                                Global.SetMessage(lblMessage, "Giá nhập phải lớn hơn 0.", false);
                                dtgReceiving.CurrentCell.Value = _oldPrice.ToString(Global.CurrencyFormat);
                            }
                            else
                            {
                                dtgReceiving.CurrentCell.Value = price.ToString(Global.CurrencyFormat);
                            }
                            ComputeGrandTotal();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private void ComputeGrandTotal()
        {
            float grandTotal = 0;
            foreach (DataGridViewRow row in dtgReceiving.Rows)
            {
                if (row.Cells[colBookID.Index].Value != null)
                {
                    float price = float.Parse(row.Cells[colReceivePrice.Index].Value.ToString());
                    int quantity = int.Parse(row.Cells[colQuantity.Index].Value.ToString());
                    grandTotal += price * quantity;
                }
            }

            txtGrandTotal.Text = grandTotal.ToString(Global.CurrencyFormat);
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            LoadDocSequenceAndCombobox();
        }

        private void dtgReceiving_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == colDel.Index && dtgReceiving[colBookID.Index, e.RowIndex].Value != null)
                {
                    if (Global.ShowMessageBoxDelete("Bạn muốn xóa dòng này ?") == DialogResult.Yes)
                    {
                        dtgReceiving.Rows.RemoveAt(e.RowIndex);
                        Global.GenerateNumber(dtgReceiving, colNumber.Index);
                        ComputeGrandTotal();
                    }

                    if (dtgReceiving.Rows.Count == 0)
                    {
                        dtgReceiving.Rows.Add(1);
                    }
                }
            }
        }

        private void dtgReceiving_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void dtgReceiving_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == colReceivePrice.Index)
            {
                if (dtgReceiving.CurrentCell.Value != null)
                {
                    _oldPrice = float.Parse(dtgReceiving.CurrentCell.Value.ToString());
                }
            }
        }

        private void SetMessage(string mess, bool isSuccess)
        {
            Global.SetMessage(lblMessage, mess, isSuccess);
        }

        private void ProcessButton()
        {
            if (Action == ActionName.Insert)
            {
                btnAdd.Visible = true;
                btnUpdate.Visible = false;
                btnDelete.Enabled = false;
                btnAdd.Enabled = true;
            }
            else
            {
                btnAdd.Visible = false;
                btnUpdate.Visible = true;
                btnDelete.Enabled = true;
            }
            dtgReceiving.ReadOnly = false;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckQuantityReceiving())
                {
                    SetMessage("Có sách có số lượng tồn lớn hơn quy định ( dòng màu đỏ ).", false);
                    return;
                }

                ReceivingListDTO receivingDto = new ReceivingListDTO();
                receivingDto.CreatedBy = Global.UserID;
                receivingDto.Description = txtDescription.Text;
                receivingDto.GrandTotal = Global.floatParse(txtGrandTotal.Text);
                receivingDto.ReceivingCode = txtReceivingCode.Text;
                receivingDto.ReceivingDate = dtpCreateDate.Value;
                receivingDto.Status = true;
                receivingDto.ListReceiving = new List<ReceivingDetailDTO>();

                foreach (DataGridViewRow row in dtgReceiving.Rows)
                {
                    if (row.Cells[colBookID.Index].Value != null)
                    {
                        ReceivingDetailDTO receiDetail = new ReceivingDetailDTO();
                        receiDetail.UnitPrice = Global.floatParse(row.Cells[colReceivePrice.Index].Value.ToString());
                        receiDetail.Quantity = Global.intParse(row.Cells[colQuantity.Index].Value.ToString());
                        receiDetail.BookID = Global.intParse(row.Cells[colBookID.Index].Value.ToString());

                        receivingDto.ListReceiving.Add(receiDetail);
                    }
                    //else
                    //{
                    //    dtgReceiving.Rows.Remove(row);
                    //}
                }

                if (receivingDto.ListReceiving.Count == 0)
                {
                    SetMessage("Phiếu nhập phải có ít nhất một sách!.", false);
                    return;
                }

                if (receiBUS.InsertReceivingList(receivingDto))
                {
                    SetMessage("Nhập sách thành công.", true);
                    dtgReceiving.Enabled = false;
                    btnAdd.Enabled = false;
                }
                else
                {
                    SetMessage("Có lỗi trong quá trình làm việc, vui lòng thử lại.", false);
                }
            }
            catch(Exception ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private bool CheckQuantityReceiving()
        {
            try
            {
                bool success = true;
                foreach (DataGridViewRow row in dtgReceiving.Rows)
                {
                    if (row.Cells[colBookID.Index].Value != null)
                    {
                        int quantity = Global.intParse(row.Cells[colStockQuantity.Index].Value);
                        if (!receiBUS.CheckQuantityReceiving(quantity))
                        {
                            success = false;
                            row.DefaultCellStyle.ForeColor = Color.Red;
                        }
                        else
                        {
                            row.DefaultCellStyle.ForeColor = Color.Black;
                        }
                    }
                }

                return success;
            }
            catch (Exception ex)
            {
                SetMessage(ex.Message, false);
                return false;
            }
        }
    }
}
